<template>
	<view class="page">
		<u-toast ref="uToast" />
		<common :tips="commonTips"></common>

		<u-cell-group :border="false" class="redpacket-box">
			<u-cell-item title="红包总金额" :arrow="false">
				<view slot="right-icon" class="input-wrapper">
					<u-input placeholder="0.00" placeholder-style="text-align: right" input-align="right" type="number"
						:clearable="false" v-model="form.amount_total" :formatter="value => value = formatAmount(value)"
						@blur="validateAmount" />
					<text class="currency">元</text>
				</view>
			</u-cell-item>

			<u-cell-item title="红包个数" :arrow="false">
				<view slot="right-icon" class="input-wrapper">
					<u-input placeholder="填写个数" placeholder-style="text-align: right" input-align="right" type="number"
						:clearable="false" v-model="form.count_total" @blur="validateCount" />
					<text class="unit">个</text>
				</view>
			</u-cell-item>

			<u-cell-item title="红包类型" @click="showTypePicker = true" :arrow="true">
				<view slot="right-icon" class="type-select">
					{{ typeMap[form.type] }}
					<!-- <u-icon name="arrow-right" color="#999" size="28"></u-icon> -->
				</view>
			</u-cell-item>

			<u-cell-item title="祝福语" :arrow="false">
				<u-input placeholder="恭喜发财 大吉大利" placeholder-style="color: #666;" input-align="right" :clearable="false"
					v-model="form.title" :border="false" />
			</u-cell-item>
		</u-cell-group>

		<view class="tips-box">
			<!-- <text class="balance-tips">当前余额：{{ money }}元</text> -->
			<text class="rule-tips">* 单个红包金额范围：0.01元 - 99999.99元</text>
		</view>

		<view class="submit-btn">
			<u-button shape="circle" :custom-style="{width: '80%', height: '88rpx'}" :ripple="true"
				@click="sendRedpacket">
				塞钱进红包
			</u-button>
		</view>

		<!-- 类型选择器 -->
		<u-picker v-model="showTypePicker" mode="selector" :default-selector="[0]" :range="typeList"
			@confirm="confirmType"></u-picker>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				commonTips: '',
				userinfo: {},
				money: 0,
				showTypePicker: false,
				typeList: ['拼手气红包', '普通红包'],
				typeMap: {
					random: '拼手气红包',
					fixed: '普通红包'
				},
				form: {
					amount_total: '',
					count_total: '',
					type: 'random',
					title: ''
				},
				redpacketdata: {} // 预定义变量
			}
		},
		onLoad() {
			this.userinfo = uni.getStorageSync('userinfo');
			this.fetchMoney();
		},
		methods: {
			// 金额格式化
			formatAmount(value) {
				return value.replace(/[^0-9.]/g, '')
					.replace(/\.{2,}/g, '.')
					.replace(/^0+(\d)/, '$1')
					.replace(/^\./, '0.')
					.replace(/(\.\d{2})./g, '$1')
			},

			// 验证金额
			validateAmount() {
				const val = parseFloat(this.form.amount_total)
				if (isNaN(val) || val <= 0) {
					this.$refs.uToast.show({
						title: '请输入有效金额',
						type: 'error'
					})
					return false
				}
				if (val > 99999.99) {
					this.$refs.uToast.show({
						title: '总金额超过限制',
						type: 'error'
					})
					return false
				}
				if (this.form.type === 'fixed') {
					const count = parseInt(this.form.count_total) || 1;
					if (count <= 0) return false;
					const perAmount = val / count;
					if (perAmount > 99999.99) {
						this.$refs.uToast.show({
							title: '单个红包金额不能超过99999.99元',
							type: 'error'
						});
						return false;
					}
				}
				return true
			},

			// 验证红包个数
			validateCount() {
				const val = parseInt(this.form.count_total)
				if (isNaN(val) || val <= 0 || val > 9999) {
					this.$refs.uToast.show({
						title: '个数需为1-9999的整数',
						type: 'error'
					})
					return false
				}
				return true
			},

			// 类型选择确认
			confirmType(e) {
				this.form.type = e[0] === 0 ? 'random' : 'fixed'
			},

			// 获取余额
			async fetchMoney() {
				try {
					const res = await this.$u.post('/api/Redpacket/userinfo', {
						im_tourists_token: this.userinfo.auth_token
					})
					this.money = res.data.money
				} catch (e) {
					console.error(e)
				}
			},
			// 发群红包
			sendRedpacket() {
				if (!this.validateAmount() || !this.validateCount()) return;

				const amount = parseFloat(this.form.amount_total);
				const count = parseInt(this.form.count_total);

				if (this.form.type === 'fixed') {
					const perAmount = amount / count;
					if (perAmount < 0.01) {
						this.$refs.uToast.show({
							title: '单个红包金额不能小于0.01元',
							type: 'error'
						});
						return;
					}
				}

				if (this.money < amount) {
					this.$refs.uToast.show({
						title: `余额不足，还需${(amount - this.money).toFixed(2)}元`,
						type: 'error',
						duration: 1500,
						callback: () => {
							uni.navigateTo({
								url: '/pages/center/recharge_shande'
							});
						}
					});
					return;
				}

				const params = {
					user_id: this.userinfo.user_id, // 假设 userinfo 中有 id 字段
					amount_total: amount.toFixed(2),
					count_total: count,
					type: this.form.type,
					title: this.form.title || '恭喜发财，大吉大利'
				};

				const token = this.userinfo.auth_token;

				this.$u.post(`/api/Redpacket/createRedpackets?im_tourists_token=${token}`, params)
					.then(res => {
						if (res.status === 'success') {
							console.log("群红包创建成功", res);

							// 构建群聊消息内容
							let redpacketdata = {
								redPackedId: res.redpacket_id,
								redpacket_type: this.form.type,
								redpacket_title: this.form.title || '恭喜发财，大吉大利',
								redpacket_total: amount,
								redpacket_count: count,
								is_group: true, // 标记为群红包,
								// 可根据具体业务补充 to_user_id，比如群ID
								memo: `[群红包] ${this.form.title || '恭喜发财，大吉大利'} 共${amount.toFixed(2)}元/${count}个`
							};
							console.log("this.redpacketdata:" + redpacketdata);
							console.log(JSON.stringify(redpacketdata, null, 2)); // 美化输出
							// 通过全局事件传给聊天界面
							uni.$emit('redpacketdatas', redpacketdata);
							// 返回聊天页
							uni.navigateBack({
								delta: 1
							});

						} else {
							this.$refs.uToast.show({
								title: res.message || '红包发送失败',
								type: 'error'
							});
						}
					})
					.catch(err => {
						console.error("红包创建异常", err);
						this.$refs.uToast.show({
							title: '红包创建异常',
							type: 'error'
						});
					});
			}

		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #f7f7f7;
		min-height: 100vh;
		padding-top: 30rpx;
	}

	.redpacket-box {
		width: 94%;
		margin: 0 auto;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

		::v-deep .u-cell {
			min-height: 100rpx;
		}
	}

	.input-wrapper {
		display: flex;
		align-items: center;

		.currency,
		.unit {
			font-size: 32rpx;
			color: #333;
			margin-left: 16rpx;
		}
	}

	.type-select {
		display: flex;
		align-items: center;
		color: #333;
		font-size: 30rpx;

		.u-icon {
			margin-left: 20rpx;
		}
	}

	.tips-box {
		padding: 30rpx 4%;
		color: #999;
		font-size: 24rpx;
		line-height: 1.8;

		.balance-tips {
			color: #e54d42;
			margin-right: 30rpx;
		}
	}

	.submit-btn {
		margin: 60rpx auto;
		display: flex;
		justify-content: center;

		::v-deep .u-btn {
			font-size: 36rpx;
			font-weight: bold;
			background: linear-gradient(45deg, #e54d42, #ff6b6b);
			color: #fff !important;
			border: none !important;
		}
	}
</style>
